﻿using IMServer.Models;
using IMServer.Services;
using IMServer.Models.Message;

namespace IMServer.Endpoints;

public static class GroupEndpoint
{
    public static RouteGroupBuilder MapGroupApi(this RouteGroupBuilder group)
    {
        group.MapPost("/create", async (HttpContext context) =>
        {
            try
            {
                var group = await context.Request.ReadFromJsonAsync<Group>();

                if (group == null)
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "请求参数错误"
                    });
                }

                if (group.Members == null || group.Members.Length < 3)
                {
                    return Results.Json(new
                    {
                        code = "1205",
                        message = "创建群组至少需要3个成员"
                    });
                }

                if (!group.Members.Contains(group.Creator))
                {
                    return Results.Json(new
                    {
                        code = "1206",
                        message = "群组创建者必须在成员列表中"
                    });
                }

                if (!await group.GenerateGroupName())
                {
                    return Results.Json(new
                    {
                        code = "1207",
                        message = "生成群组名称失败"
                    });
                }

                group.GenerateGroupId();


                var createdGroup = await GroupDbService.Instance.CreateGroupAsync(group);

                // 将群组ID添加到每个成员的Groups中
                foreach (var member in createdGroup.Members)
                {
                    await UserDbService.Instance.AddGroupToUserAsync(member, createdGroup.GroupId);
                    if (member != createdGroup.Creator)
                    {
                        // 发送初始化群组通知
                        var initialGroupNotification = new InitialGroupNotification
                        {
                            MessageId = Guid.NewGuid().ToString(),
                            SenderId = "0000000000",
                            SenderName = "系统",
                            SenderAvatar = "",
                            ReceiverId = member,
                            GroupId = createdGroup.GroupId,
                            GroupName = createdGroup.GroupName,
                            GroupAvatar = createdGroup.Avatar,
                            Creator = createdGroup.Creator
                        };
                        await WebSocketManager.Instance.SendMessageToUserAsync(member,
                            initialGroupNotification.ToJson());
                    }
                }

                return Results.Json(new
                {
                    code = "0000",
                    message = "创建成功",
                    data = new
                    {
                        groupId = createdGroup.GroupId,
                        groupName = createdGroup.GroupName,
                        groupAvatar = createdGroup.Avatar,
                        creator = createdGroup.Creator,
                        adminId = createdGroup.AdminId,
                        members = createdGroup.Members
                    }
                });
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5200",
                    message = $"创建群组失败: {ex.Message}"
                });
            }
        });

        //根据群组ID获取群组信息,包括群组信息和群组成员信息
        group.MapPost("/groupinfo", async (HttpContext context) =>
        {
            try
            {
                // 直接解析 JSON 数据为动态类型
                var requestGroup = await context.Request.ReadFromJsonAsync<Group>();
                var groupId = requestGroup?.GroupId;

                if (string.IsNullOrEmpty(groupId))
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "群组ID不能为空"
                    });
                }

                var group = await GroupDbService.Instance.GetGroupByIdAsync(groupId);

                if (group == null)
                {
                    return Results.Json(new
                    {
                        code = "1104",
                        message = "群组不存在"
                    });
                }

                var members = await UserDbService.Instance.GetUsersByIdsAsync(group.Members);

                return Results.Json(new
                {
                    code = "0000",
                    message = "获取成功",
                    data = new
                    {
                        group = new
                        {
                            groupId = group.GroupId,
                            groupName = group.GroupName,
                            avatar = group.Avatar,
                            creator = group.Creator,
                            adminId = group.AdminId,
                            members = group.Members
                        },
                        members = members?.Select(m => new
                        {
                            userId = m.UserId,
                            userName = m.UserName,
                            avatar = m.Avatar
                        })
                    }
                });
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5101",
                    message = $"数据库查询错误: {ex.Message}"
                });
            }
        });

        group.MapPost("/updatename", async (HttpContext context) =>
        {
            try
            {
                // 解析请求体
                var request = await context.Request.ReadFromJsonAsync<UpdateGroupNameRequest>();

                if (request == null || string.IsNullOrEmpty(request.UserId) ||
                    string.IsNullOrEmpty(request.GroupId) || string.IsNullOrEmpty(request.NewGroupName))
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "请求参数错误"
                    });
                }

                // 获取群组信息
                var group = await GroupDbService.Instance.GetGroupByIdAsync(request.GroupId);
                if (group == null)
                {
                    return Results.Json(new
                    {
                        code = "1104",
                        message = "群组不存在"
                    });
                }

                // 检查用户是否为群主
                if (group.Creator != request.UserId)
                {
                    return Results.Json(new
                    {
                        code = "1301",
                        message = "您不是群主"
                    });
                }

                // 更新群组名称
                var success = await GroupDbService.Instance.UpdateGroupAsync(request.GroupId, request.NewGroupName);
                if (!success)
                {
                    return Results.Json(new
                    {
                        code = "1302",
                        message = "修改群组名称失败"
                    });
                }

                // 先返回成功消息
                var response = Results.Json(new
                {
                    code = "0000",
                    message = "修改成功",
                    data = new { groupName = request.NewGroupName }
                });

                // 异步发送通知
                _ = Task.Run(async () =>
                {
                    foreach (var member in group.Members)
                    {
                        if (member != request.UserId)
                        {
                            var updateGroupNameNotification = new GroupNameUpdateNotification
                            {
                                MessageId = Guid.NewGuid().ToString(),
                                SenderName = "系统",
                                SenderId = "0000000000",
                                SenderAvatar = "",
                                ReceiverId = member,
                                GroupId = request.GroupId,
                                GroupName = request.NewGroupName
                            };
                            await WebSocketManager.Instance.SendMessageToUserAsync(member,
                                updateGroupNameNotification.ToJson());
                        }
                    }
                });

                return response;
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5200",
                    message = $"修改群组名称失败: {ex.Message}"
                });
            }
        });

        group.MapPost("/updateavatar", async (HttpContext context) =>
        {
            try
            {
                if (!context.Request.HasFormContentType)
                {
                    return Results.Json(new
                    {
                        code = "1001",
                        message = "Content type必须是multipart/form-data"
                    });
                }

                var form = await context.Request.ReadFormAsync();

                // 验证必要字段
                if (string.IsNullOrEmpty(form["UserId"]) || string.IsNullOrEmpty(form["GroupId"]))
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "UserId和GroupId不能为空"
                    });
                }

                var userId = form["UserId"].ToString();
                var groupId = form["GroupId"].ToString();

                // 获取群组信息
                var group = await GroupDbService.Instance.GetGroupByIdAsync(groupId);
                if (group == null)
                {
                    return Results.Json(new
                    {
                        code = "1104",
                        message = "群组不存在"
                    });
                }

                // 检查用户是否为群主
                if (group.Creator != userId)
                {
                    return Results.Json(new
                    {
                        code = "1301",
                        message = "只有群主才能修改群头像"
                    });
                }

                // 处理头像文件
                var avatarFile = form.Files.GetFile("Avatar");
                if (avatarFile == null)
                {
                    return Results.Json(new
                    {
                        code = "1202",
                        message = "请上传头像文件"
                    });
                }

                // 验证文件类型
                if (!avatarFile.ContentType.StartsWith("image/"))
                {
                    return Results.Json(new
                    {
                        code = "1203",
                        message = "只允许上传图片文件"
                    });
                }

                // 上传到OSS并获取URL
                string avatarUrl = await OssService.Instance.UploadFileAsync(avatarFile);

                // 更新群组头像
                var success = await GroupDbService.Instance.UpdateGroupAsync(groupId, avatar: avatarUrl);
                if (!success)
                {
                    return Results.Json(new
                    {
                        code = "1302",
                        message = "修改群头像失败"
                    });
                }

                // 返回成功消息
                var response = Results.Json(new
                {
                    code = "0000",
                    message = "修改成功",
                    newAvatar = avatarUrl
                });

                // 发送群头像修改通知
                _ = Task.Run(async () =>
                {
                    foreach (var member in group.Members)
                    {
                        if (member != userId)
                        {
                            var updateGroupAvatarNotification = new GroupAvatarUpdateNotification
                            {
                                MessageId = Guid.NewGuid().ToString(),
                                SenderName = "系统",
                                SenderId = "0000000000",
                                SenderAvatar = "",
                                ReceiverId = member,
                                GroupId = groupId,
                                GroupAvatar = avatarUrl
                            };
                            await WebSocketManager.Instance.SendMessageToUserAsync(member,
                                updateGroupAvatarNotification.ToJson());
                        }
                    }
                });

                return response;
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5200",
                    message = $"修改群头像失败: {ex.Message}"
                });
            }
        });

        group.MapPost("/joinapply", async (HttpContext context) =>
        {
            try
            {
                var joinGroupReq = await context.Request.ReadFromJsonAsync<JoinGroupRequest>();
                if (joinGroupReq == null)
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "无效的请求体"
                    });
                }

                // 验证群组是否存在
                var group = await GroupDbService.Instance.GetGroupByIdAsync(joinGroupReq.GroupId);
                if (group == null)
                {
                    return Results.Json(new
                    {
                        code = "1104",
                        message = "群组不存在"
                    });
                }

                // 验证用户是否已经在群组中
                if (group.Members.Contains(joinGroupReq.SenderId))
                {
                    return Results.Json(new
                    {
                        code = "1205",
                        message = "您已经是群成员"
                    });
                }

                joinGroupReq.GenerateMessageId();
                joinGroupReq.Content = $"{joinGroupReq.SenderName} 请求加入群组 {group.GroupName}";
                joinGroupReq.ReceiverId = group.Creator; // 设置接收者为群主
                joinGroupReq.GroupName = group.GroupName;

                // 通过WebSocket发送消息给群主
                var success = await WebSocketManager.Instance.SendMessageToUserAsync(
                    group.Creator,
                    joinGroupReq.ToJson()
                );

                // 将请求存入群主的待处理消息箱
                await PendingRequestBoxesDbService.Instance.InsertPendingRequestAsync(
                    group.Creator,
                    joinGroupReq
                );

                return Results.Json(new
                {
                    code = "0000",
                    message = success ? "入群请求已发送" : "入群请求已保存，群主当前不在线"
                });
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5200",
                    message = $"申请加入群组失败: {ex.Message}"
                });
            }
        });

        group.MapPost("/joinresponse", async (HttpContext context) =>
        {
            try
            {
                var response = await context.Request.ReadFromJsonAsync<JoinGroupResponse>();
                if (response == null)
                {
                    return Results.Json(new
                    {
                        code = "1201",
                        message = "无效的请求体"
                    });
                }

                // 验证群组是否存在
                var _group = await GroupDbService.Instance.GetGroupByIdAsync(response.GroupId);
                if (_group == null)
                {
                    return Results.Json(new
                    {
                        code = "1104",
                        message = "群组不存在"
                    });
                }

                // 验证是否为群主操作
                if (_group.Creator != response.SenderId)
                {
                    return Results.Json(new
                    {
                        code = "1301",
                        message = "只有群主可以处理入群申请"
                    });
                }

                response.GenerateMessageId();

                // 如果同意加入群组
                if (response.Accepted)
                {
                    // 将用户添加到群组成员列表
                    var addToGroupSuccess =
                        await GroupDbService.Instance.AddMemberAsync(response.GroupId, response.ReceiverId);
                    // 将群组添加到用户的群组列表
                    var addToUserSuccess =
                        await UserDbService.Instance.JoinGroupAsync(response.ReceiverId, response.GroupId);

                    if (!addToGroupSuccess || !addToUserSuccess)
                    {
                        return Results.Json(new
                        {
                            code = "1302",
                            message = "添加群组成员失败"
                        });
                    }

                    response.Content = $"群主已同意您加入群组 {response.GroupName}";
                }
                else
                {
                    response.Content = $"群主已拒绝您加入群组 {response.GroupName}";
                }

                // 通过WebSocket发送响应消息给申请人
                var success = await WebSocketManager.Instance.SendMessageToUserAsync(
                    response.ReceiverId,
                    response.ToJson()
                );

                // 将响应存入申请人的待处理消息箱
                await PendingRequestBoxesDbService.Instance.InsertPendingRequestAsync(
                    response.ReceiverId,
                    response
                );

                return Results.Json(new
                {
                    code = "0000",
                    message = success ? (response.Accepted ? "已同意入群申请" : "已拒绝入群申请") : "响应已保存，申请人当前不在线"
                });
            }
            catch (Exception ex)
            {
                return Results.Json(new
                {
                    code = "5200",
                    message = $"处理入群申请失败: {ex.Message}"
                });
            }
        });

        return group;
    }



    public class UpdateGroupNameRequest
    {
        public string UserId { get; set; } = null!;
        public string GroupId { get; set; } = null!;
        public string NewGroupName { get; set; } = null!;
    }
}